package lvtu.opencv.worker;

import static com.googlecode.javacv.cpp.opencv_core.cvLoad;

import java.util.regex.Pattern;

import lvtu.opencv.bean.Pic;
import lvtu.opencv.frontier.FaceFrontier;
import lvtu.opencv.frontier.Frontier;
import lvtu.opencv.frontier.NonFaceFrontier;
import lvtu.opencv.util.ConfigUtils;
import lvtu.opencv.util.FaceDetection;
import lvtu.opencv.util.HttpUtil;
import lvtu.opencv.util.IO;
import lvtu.opencv.util.PicUtil;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.javacv.cpp.opencv_objdetect.CvHaarClassifierCascade;

public class Worker implements Runnable {

	private static final Logger logger = LoggerFactory.getLogger(Worker.class);

	protected int myId;

	private Thread myThread;

	private boolean isWaiting;

	private WorkController controller;

	public static final String HOTS_URL = "http://img.qunarzz.com";
	public static final String HOTS_URL_CDN = "http://img1.qunarzz.com";

	private final static Pattern FILTERS = Pattern
			.compile(".*(\\.(bmp|gif|jpe?g" + "|png|tiff?))$");

	private final String CASCADE_FILE = ConfigUtils.getCascade();

	private final CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(
			cvLoad(CASCADE_FILE));

	/**
	 * Initializes the current instance of the crawler
	 * 
	 * @param myId
	 *            the id of this crawler instance
	 * @param crawlController
	 *            the controller that manages this crawling session
	 */
	public void init(int myId, WorkController controller) {
		this.myId = myId;
		this.isWaiting = false;
		this.controller = controller;
	}

	/**
	 * Get the id of the current crawler instance
	 * 
	 * @return the id of the current crawler instance
	 */
	public int getMyId() {
		return myId;
	}

	/**
	 * This function is called just before starting the crawl by this crawler
	 * instance. It can be used for setting up the data structures or
	 * initializations needed by this crawler instance.
	 */
	public void onStart() {
		// System.out.println("froniter in poccess length:"+frontier.getNumberOfAssignedPages());
		// System.out.println("froniter length:"+frontier.getQueueLength());
	}

	/**
	 * This function is called just before the termination of the current
	 * crawler instance. It can be used for persisting in-memory data or other
	 * finalization tasks.
	 */
	public void onBeforeExit() {
	}

	public void run() {
		onStart();
		while (true) {
			if (controller.finished) {
				isWaiting = true;
				return;
			}

			Pic pic = Frontier.take();

			if (pic == null) {
				isWaiting = true;
				try {
					Thread.sleep(10000);
					logger.info("There is no pic in Frontier ,Worker-" + myId
							+ " is waitting 3 s.");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				isWaiting = false;

				HttpUtil http = new HttpUtil();
				try {
					// String filename = ConfigUtils.getTempPath() + "worker"
					// + myId + StringUtils.substring(pic.getUrl(),
					// pic.getUrl().lastIndexOf("."));
					String filename = ConfigUtils.getTempPath() + "worker"
							+ myId + ".jpg";
				   //System.out.println(pic.getUrl());
					if(StringUtils.isBlank(pic.getUrl())){
						logger.error("图片url为空,picId:"+pic.getId());
						throw new Exception();
					}
					String href = pic.getUrl().toLowerCase();
					if (!FILTERS.matcher(href).matches()) {
						pic.setIsFace(1);
						FaceFrontier.put(pic);
						continue;
					}

					// String cdnUrl =
					// StringUtils.replace(pic.getUrl(),"img.qunarzz.com","img1.qunarzz.com");

					String cdnUrl = PicUtil.getMiniUrl(pic.getUrl(), "600x400");
					// System.out.println(cdnUrl);
					// if(pic.getUrl().endsWith(".png")||pic.getUrl().endsWith(".PNG")){
					//
					// http.getAndSaveData(StringUtils.replace(pic.getUrl(),"img.qunarzz.com","img1.qunarzz.com"),
					// filename);
					// }else{
					http.getAndSaveData(cdnUrl, filename);
					// }

					if (FaceDetection.isFace(filename, cascade)) {
						pic.setIsFace(1);
						FaceFrontier.put(pic);
						System.out.println("该图片包含人物肖像:" + pic.toString());
					} else {
						pic.setIsFace(2);
						NonFaceFrontier.put(pic);
					}

					// IO.deleteFile(filename);

				} catch (Exception e) {
					e.printStackTrace();
					FaceFrontier.put(pic);
					continue;
				}
			}

		}
	}

	public Thread getThread() {
		return myThread;
	}

	public void setThread(Thread myThread) {
		this.myThread = myThread;
	}

	public boolean isWaiting() {
		return isWaiting;
	}

}
